from appserver import db_store
import traceback

class TokenWithButton(db_store.Model):
	__tablename__="tokens_with_buttons"
	__bind_key__="main"

	# id=db_store.Column(db_store.Integer,primary_key=True)
	token_id=db_store.Column(db_store.Integer,db_store.ForeignKey("tokens.id"),primary_key=True,nullable=False)
	# module_id=db_store.Column(db_store.Integer,db_store.ForeignKey("modules.id"),primary_key=True,nullable=False)
	button_id=db_store.Column(db_store.Integer,db_store.ForeignKey("buttons.id"),primary_key=True)
	user_id=db_store.Column(db_store.Integer,db_store.ForeignKey("users.id"),primary_key=True)

	def __repr__(self):
		return "<TokenWithButton %d+%d>" %(self.token_id,self.button_id)

	def save(self):
		if self.token_id is None:
			print("-------------------------TokenWithButton save error: token_id cannot be empty")
			return -1
		if self.button_id is None:
			print("-------------------------TokenWithButton save error: button_id cannot be empty")
			return -3
		try:
			db_store.session.add(self)
			# print(self)
			db_store.session.commit()
			return 0
		except:
			print("-------------------------table tokens_with_buttons write error:\n------------------------------\n%s\n---------------------------" %(traceback.format_exc()))
			db_store.session.rollback()
			return -7

	def delete(self):
		try:
			db_store.session.delete(self)
			db_store.session.commit()
			return 0
		except:
			print("-------------------------TokenWithButton delete error:\n----------------------\n%s\n---------------------" %(traceback.format_exc()))
			db_store.session.rollback()
			return -1

	@staticmethod
	def add_button_to_token(the_token,the_button):
		# 为指定token添加相应button
		new_connector=TokenWithButton()
		new_connector.module_id=the_button.module_id
		new_connector.user_id=the_token.user_id
		new_connector.token_id=the_token.id
		new_connector.button_id=the_button.id
		ret=new_connector.save()
		if ret==0:
			return 0
		print("add_button_to_token error: tokens_with_buttons save error")
		return -1

	@staticmethod
	def get_token_with_button_by_token_id(token_id):
		return TokenWithButton.query.filter_by(token_id=token_id).all()
